import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.io.File;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.*;

public class CodeGenerator {

    // ✅ 修复：只到项目根目录
    private static final String OUTPUT_PATH = System.getProperty("user.dir") + "/service/service-activity";

    // 数据库连接
    private static final String URL = "jdbc:mysql://localhost:3306/shequ-activity?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";

    // 包名
    private static final String PARENT_PACKAGE = "com.guigu.ssyx.activity";

    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 2. 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(OUTPUT_PATH + "/src/main/java") // ✅ 正确路径
                .setAuthor("liuyang")
                .setOpen(false)
                .setFileOverride(true)
                .setIdType(IdType.AUTO)
                .setSwagger2(true)
                .setServiceName("%sService")
                .setServiceImplName("%sServiceImpl")
                .setMapperName("%sMapper")
                .setXmlName("%sMapper")
                .setBaseResultMap(true)
                .setBaseColumnList(true);
        mpg.setGlobalConfig(gc);

        // 3. 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL)
                .setDriverName(DRIVER_NAME)
                .setUsername(USERNAME)
                .setPassword(PASSWORD)
                .setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4. 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PARENT_PACKAGE)
                .setEntity("entity")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setController("controller");

        // ✅ 关键：设置 XML 输出路径
        Map<String, String> pathInfo = new HashMap<>();
        pathInfo.put(ConstVal.XML_PATH, OUTPUT_PATH + "/src/main/resources/mapper");
        // ✅ 添加这一行：明确指定 Mapper.java 的输出路径
        pathInfo.put(ConstVal.MAPPER_PATH, OUTPUT_PATH + "/src/main/java/com/guigu/ssyx/activity/mapper");
        pc.setPathInfo(pathInfo);

        mpg.setPackageInfo(pc);

        // 5. 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setEntityLombokModel(true)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                // ✅ 建议手动输入表名测试
                .setInclude(getAllTableNames()) // 需要生成的表
                .setLogicDeleteFieldName("is_deleted")
                .setEntityTableFieldAnnotationEnable(true)
                // ✅ 修复包名
                .setSuperEntityClass("com.guigu.ssyx.model.base.BaseEntity")
                // ✅ 明确表前缀，比如 activity_info → 前缀 activity_
                .setSuperEntityColumns("id", "create_time", "update_time", "is_deleted");

        mpg.setStrategy(strategy);

        // 6. 模板引擎
        mpg.setTemplateEngine(new VelocityTemplateEngine());

        // ✅ 执行前确保目录存在
        File xmlDir = new File(OUTPUT_PATH + "/src/main/resources/mapper");
        if (!xmlDir.exists()) {
            xmlDir.mkdirs();
        }

        // 执行生成
        mpg.execute();
        System.out.println("✅ 代码生成完成！");
    }

    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + "：");
        if (scanner.hasNext()) {
            return scanner.next();
        }
        throw new RuntimeException("请输入正确的" + tip + "！");
    }


    private static String[] getAllTableNames() {
        try (java.sql.Connection conn = java.sql.DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData meta = conn.getMetaData();
            java.sql.ResultSet rs = meta.getTables("shequ-activity", null, "%", new String[]{"TABLE"});

            java.util.List<String> tables = new java.util.ArrayList<>();
            while (rs.next()) {
                tables.add(rs.getString("TABLE_NAME"));
            }
            return tables.toArray(new String[0]);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取表名失败", e);
        }
    }
}